<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="90" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_payments"
      height="auto"
      :columns="columns"
      :datakey="'rows'"
      selectionType="single"
      :onSyncTableData="syncTableFun"
      :defaultSelections="defaultSelections"
      :onRowSelectChange="onRowSelectChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
    </FilterTable>
    <FilterTable
      ref="table1"
      height="auto"
      :columns="columns1"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns1 = columns)"
      :onSyncTableData="invoiceSyncTableFun"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" :disabled="confirmBtnLoading" :loading="confirmBtnLoading" @click="saveDialog">确 定</el-button>
      <el-button @click="closeDialog(true)">取 消</el-button>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { getUserId } from '@/assets/js/auth';
import { isAuthorized } from '@/utils/index';
import { getBalance, getAllUser, gathering } from '@/api/repair/repairFinance/index.js';

export default {
  name: 'Payments',
  mixins: [dictionary],
  props: ['rowData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      columns1: this.createTableColumns1(),
      money: null, // 收款总额（多条结算单之和）
      balance: null, // 预存金余额
      confirmBtnLoading: false,
      singleSelectRow: {},
      defaultSelections: [],
      BALA_PAYOBJ_ID: ''
    };
  },
  mounted() {
    this.getEmployee();
  },
  methods: {
    onRowSelectChange(rows) {
      if (rows.length) {
        this.singleSelectRow = { ...rows[0] };
        this.BALA_PAYOBJ_ID = rows[0].BALA_PAYOBJ_ID;
      }
    },
    invoiceSyncTableFun(tableData) {
      console.log('tableData:', tableData);
      // if (tableData && tableData.length) {
      //   let sum = 0;
      //   tableData.forEach(item => {
      //     sum += Number(item.INVOICE_AMOUNT) || 0;
      //   });
      //   // this.money = sum; // 需要收的总数
      //   debugger;
      //   if (sum > this.money) {
      //     this.$notify.warning({ title: '提示信息', message: '发票总额大于收款金额' });
      //     tableData[tableData.length].INVOICE_AMOUNT = 0;
      //   }
      //   // this.formList.find(x => x.fieldName === 'receiveAmount').initialValue = sum.toFixed(2);
      // }
    },
    // 获取回调数据
    syncTableFun(tableData) {
      if (tableData && tableData.length) {
        let sum = 0;
        tableData.forEach(item => {
          sum += Number(item.RECEIVE_AMOUNT) || 0;
        });
        this.money = sum; // 需要收的总数
        console.log(sum);
        if (this.balance > 0 && this.money > 0) {
          // 正收款且有预存金
          let usingPrePay = this.formList.find(x => x.fieldName === 'usingPrePay').initialValue;
          sum = sum - (Number(usingPrePay) || 0);
        }
        this.formList.find(x => x.fieldName === 'receiveAmount').initialValue = sum.toFixed(2);
      }
    },

    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'paymentObjectCode',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'paymentObjectName',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: [],
          label: '经手人',
          fieldName: 'handler',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: this.createDictList('8044', [80441010, 80441011]),
          label: '付款方式',
          fieldName: 'payTypeCode',
          rules: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
          initialValue: 80441001
        },
        {
          type: 'INPUT',
          label: '支票号码',
          fieldName: 'checkNo'
        },
        {
          type: 'DATE',
          label: '收款日期',
          dateType: 'datetime',
          fieldName: 'receiveDate'
        },
        {
          type: 'INPUT_NUMBER',
          label: '可用余款',
          precision: 2,
          fieldName: 'prePay',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '本次使用余款',
          precision: 2,
          fieldName: 'usingPrePay',
          initialValue: 0,
          // min: 0,
          change: val => {
            if (!val) {
              val = 0;
            }
            this.changeBalance(val);
          }
        },
        {
          type: 'INPUT',
          label: '收款金额',
          precision: 2,
          // min: 0,
          disabled: true,
          fieldName: 'receiveAmount'
          // rules: [{ required: true, message: '请输入收款金额', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          itemList: this.createDictList('1004'),
          label: '销账标志',
          fieldName: 'writeoffTag',
          initialValue: 10041002
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          sorter: true
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          precision: 2,
          sorter: true,
          editable: true,
          defaultEditable: true,
          editRequired: true,
          editType: 'number'
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.PAY_OFF, '1004')}</span>;
          }
        },
        {
          title: '是否已开票',
          dataIndex: 'INVOICE_TAG',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.INVOICE_TAG, '1004')}</span>;
          }
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 110,
          // fixed: 'left',
          render: props => {
            return (
              <el-button
                size="mini"
                type="text"
                onClick={() => {
                  this.$refs.table1.$refs.pageTable.EXECUTE_DELETE([props.row]);
                }}
              >
                删除
              </el-button>
            );
          }
        },
        {
          title: '发票类型',
          dataIndex: 'INVOICE_TYPE_CODE',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editRequired: true,
          dictItems: this.createDictList('1111'),
          editType: 'select',
          editItems: this.createDictList('1111')
        },
        {
          title: '发票金额',
          dataIndex: 'INVOICE_AMOUNT',
          precision: 2,
          min: 0,
          sorter: true,
          editable: true,
          defaultEditable: true,
          editRequired: true,
          editType: 'number'
        },
        {
          title: '发票号',
          dataIndex: 'INVOICE_NO',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editRequired: true,
          editType: 'text'
        },
        {
          title: '发票日期',
          dataIndex: 'INVOICE_DATE',
          sorter: true,
          width: 150,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'date-picker'
        },
        {
          title: '发票抬头',
          dataIndex: 'CUSTOMER_CODE',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editRequired: true,
          editType: 'text'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          width: 100,
          editable: true,
          defaultEditable: true,
          editType: 'text'
        }
      ];
    },
    // 初始化页面
    openModel(data) {
      console.log('传入', data);
      this.getBalance(data[0].PAYMENT_OBJECT_CODE);
      let row = { ...data[0] };
      // 调用openModel时，data中的数据还没有初始化完毕
      this.BALA_PAYOBJ_ID = data[0].BALA_PAYOBJ_ID;
      this.$nextTick(() => {
        this.singleSelectRow = row; // 默认选中第一条
        this.defaultSelections.push(row);
      });
      if (data && data.length) {
        data.forEach(x => {
          x.RECEIVE_AMOUNT = x.NOT_RECEIVED_AMOUNT;
        });
      }
      this.formList.find(item => item.fieldName === 'paymentObjectCode').initialValue = data[0].PAYMENT_OBJECT_CODE;
      this.formList.find(item => item.fieldName === 'paymentObjectName').initialValue = data[0].PAYMENT_OBJECT_NAME;
      this.formList.find(item => item.fieldName === 'receiveDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
      this.formList.find(item => item.fieldName === 'handler').initialValue = getUserId();
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
    },
    formChangeHandle(val) {
      // this.saveData = val;
    },
    async getEmployee() {
      const res = await getAllUser();
      this.formList.find(item => item.fieldName === 'handler').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    // 获取预收款信息 - 预存金
    async getBalance(id) {
      const res = await getBalance({ ownerNo: id });
      this.balance = this.formList.find(item => item.fieldName === 'prePay').initialValue = res.data.toFixed(2);
    },
    changeBalance(val) {
      if (this.formList.find(item => item.fieldName === 'receiveAmount').initialValue) {
        this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = this.money - val;
      }
      // this.formList.find(item => item.fieldName === 'prePay').initialValue = this.balance - val;
      if (val > this.balance) {
        this.$notify.warning({ title: '提示信息', message: '本次使用余额不得大于可用余额!' });
        this.formList.find(item => item.fieldName === 'usingPrePay').initialValue = Math.min(this.mony, this.balance, val);
      }
    },
    addHandle() {
      let obj = {
        INVOICE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
        BALA_PAYOBJ_ID: this.BALA_PAYOBJ_ID,
        INVOICE_TYPE_CODE: undefined, // ELEC - 其他 CAF1-普通发票 CAF2-增值税发票...
        CUSTOMER_CODE: undefined,
        CUSTOMER_NAME: undefined,
        INVOICE_AMOUNT: this.money
      };
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(obj);
    },
    async saveDialog() {
      /**
       *  校验逻辑：
       *  1.使用余额不能大于预存金
       *  2.使用余额不能大于收款金额(正收款)
       *  3.收款金额不能大于未收金额（单条行项目）
       *  4.负收款金额不能大于已收款金额（不能多退款）
       */
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      let usingPrePay = data.usingPrePay || 0;
      let flag = true;

      if (usingPrePay > this.balance) {
        // 校验条件1
        this.$notify.error({ title: '提示信息', message: '本次使用余额不得大于可用余额!' });
        return;
      }
      if (usingPrePay > this.money && this.money > 0) {
        // 校验条件2
        this.$notify.warning({ title: '提示信息', message: '本次使用余额不得大于单据的收款金额!' });
        return;
        // this.formList.find(item => item.fieldName === 'usingPrePay').initialValue = Math.min(this.mony, this.balance, val);
      }

      let tableData = _.cloneDeep(this.$refs.table.$refs.pageTable.dataSource);
      let sum = 0;
      for (const item of tableData) {
        sum += Number(item.RECEIVE_AMOUNT);
        if (item.RECEIVE_AMOUNT > item.NOT_RECEIVED_AMOUNT && item.NOT_RECEIVED_AMOUNT > 0) {
          flag = false; // 校验条件3
        }
        if (item.NOT_RECEIVED_AMOUNT > 0) {
          if (Number(item.RECEIVE_AMOUNT) + item.RECEIVED_AMOUNT < 0) {
            // 校验条件4
            this.$notify.error({ title: '提示信息', message: '收款金额与已收款金额之和不能小于0!' });
            return;
          }
        }
      }
      if (!flag) {
        this.$notify.warning({ title: '提示信息', message: '收款金额大于未收款金额，不能收款' });
        return;
      }

      // 校验发票总金额
      let invoiceError = this.$refs.table1.GET_REQUIRED_ERROR();
      if (invoiceError) return this.$notify.error({ title: '提示信息', message: '请填写发票的必填项！！！' });
      let invoiceTableData = _.cloneDeep(this.$refs.table1.$refs.pageTable.dataSource);
      let invoiceSum = 0;
      if (invoiceTableData && invoiceTableData.length) {
        invoiceTableData.forEach(item => {
          invoiceSum += Number(item.INVOICE_AMOUNT) || 0;
        });
        if (invoiceSum > this.money) {
          this.$notify.warning({ title: '提示信息', message: '发票总额大于收款金额' });
          invoiceTableData[invoiceTableData.length].INVOICE_AMOUNT = 0;
          return;
        }
      }

      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.confirmBtnLoading = true;
          for (const item of tableData) {
            item.PAY_OFF = item.PAY_OFF == 10041001 ? 10041002 : 10041001;
          }
          let params = {
            ownerNo: data.paymentObjectCode,
            ...data,
            paymentObjectList: tableData,
            invoiceList: invoiceTableData,
            invoiceTag: !!invoiceTableData.length ? 10041001 : 10041002,
            prePay: this.balance // 覆盖prepay，后台需要上次的余额做校验
          };
          let res = await gathering(params);
          this.confirmBtnLoading = false;
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '保存成功!' });
            this.closeDialog(true);
          }
        })
        .catch(() => {
          this.confirmBtnLoading = false;
        });
    },
    closeDialog(val) {
      this.$emit('close', val);
    }
  }
};
</script>

<style lang="less" scoped></style>
